import { Injectable } from '@angular/core'
import {Hero} from './hero'
import {HEROES} from './mock-heroes'
import {Http, Headers} from '@angular/http'
import {Logger} from './logger.service'
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HeroService {
    private heroesUrl = 'app/heroes';
    private headers = new Headers({ 'Content-Type': 'application/json' });
    constructor(private http: Http, private logger: Logger, private isAuthorized: boolean) {

    }
    getHeros(): Promise<Hero[]> {
        let auth = this.isAuthorized ? 'authorized ' : 'unauthorized';
        this.logger.log(`Getting heroes for ${auth} user.`);
        return this.http.get(this.heroesUrl)
            .toPromise()
            .then(response => {
                let heros: Hero[] = <Hero[]>response.json().data;
                return heros.filter(hero => this.isAuthorized || !hero.isSecret)
            })
            .catch()
        //return Promise.resolve(HEROES);
    }
    getHeroesSlowly(): Promise<Hero[]> {
        return new Promise<Hero[]>(resolve =>
            setTimeout(() => resolve(HEROES), 2000)
        );
    }
    getHero(id: number): Promise<Hero> {
        return this.getHeros().then(heros => heros.find(hero => hero.id == id));
    }

    update(hero: Hero): Promise<Hero> {
        const url = `${this.heroesUrl}/${hero.id}`;
        return this.http
            .put(url, JSON.stringify(hero), { headers: this.headers })
            .toPromise()
            .then(() => hero)
            .catch(this.handleError);
    }

    create(name: string): Promise<Hero> {
        return this.http
            .post(this.heroesUrl, JSON.stringify({ name: name }), { headers: this.headers })
            .toPromise()
            .then(res => res.json().data)
            .catch(this.handleError);
    }

    delete(id: number): Promise<void> {
        let url = `${this.heroesUrl}/${id}`;
        return this.http.delete(url, { headers: this.headers })
            .toPromise()
            .then(() => null)
            .catch(this.handleError);
    }


    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }

}